﻿using UnityEngine;
using System.Collections;

public class EnemySpawner : ObjectSpawner
{	
	public enum EnemySpawnType
	{
		ONCREATION = 0,
		ONLEVELSTART,
		ONLEVELENDREACHED
	}

	public Enemy.EnemyType m_EnemyToSpawn;
	public EnemySpawnType m_EnemySpawnType;

	private LevelPartInfo m_LevelPart;

	protected override void Start ()
	{
		m_LevelPart = (LevelPartInfo)aTransform.GetComponentUpwards(typeof(LevelPartInfo));

		switch(m_EnemySpawnType)
		{
		case EnemySpawnType.ONCREATION:
			Spawn ();
			break;
		case EnemySpawnType.ONLEVELSTART:
			m_LevelPart.m_OnLevelStart += Spawn;
			break;
		case EnemySpawnType.ONLEVELENDREACHED:
			m_LevelPart.m_OnLevelEndReached += Spawn;
			break;
		}

		EnemyManager.Instance.RegisterEnemyPerLevel(m_LevelPart);
	}

	protected override void Spawn ()
	{
		GameObject go = (GameObject)Instantiate(EnemyManager.Instance.GetPrefabByEnemyType(m_EnemyToSpawn));
		Enemy enemy = go.GetComponent<Enemy>();
		
		enemy.m_LevelOwner = m_LevelPart;

		if(m_LevelPart.m_Type == LevelManager.LevelType.FORWARDONLY)
		{
			enemy.m_AutoKill = true;
		}

		enemy.aTransform.position = aTransform.position;
		enemy.SetTarget(m_TargetPosition.position);
		enemy.aTransform.SetParent(EnemyManager.Instance.transform);

		base.Spawn();
	}

	private void OnDestroy()
	{
		if(m_LevelPart != null)
		{
			switch(m_EnemySpawnType)
			{
			case EnemySpawnType.ONLEVELSTART:
				m_LevelPart.m_OnLevelStart -= Spawn;
				break;
			case EnemySpawnType.ONLEVELENDREACHED:
				m_LevelPart.m_OnLevelEndReached -= Spawn;
				break;
			}
		}
	}
	
	//private void OnDrawGizmosSelected()
	protected override void OnDrawGizmos()
	{
		//Gizmos.DrawGUITexture(new Rect(aTransform.position.x, aTransform.position.y, m_GizmoSize.x, m_GizmoSize.y), m_GizmoVisual);
		base.OnDrawGizmos();
		//Gizmos.DrawGUITexture(m_GizmoRect, m_GizmoVisual);
		//Gizmos.DrawLine(aTransform.position, m_TargetPosition.position);
		Gizmos.color = Color.green;
		Gizmos.DrawLine(aTransform.position, m_TargetPosition.position);
	}
}
